package com.tuyrt.`as`.proj.main.fragment.home

import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView.LayoutManager
import com.tuyrt.`as`.proj.common.ui.component.HiAbsListFragment
import com.tuyrt.`as`.proj.main.model.HomeModel
import com.tuyrt.hi.library.restful.annotation.CacheStrategy
import com.tuyrt.hi.ui.item.HiDataItem

/**
 * author: Administrator on 2021/7/6.
 * desc:
 */
class HomeTabFragment : HiAbsListFragment() {

    private lateinit var viewModel: HomeViewModel
    private var categoryId: String? = null
    val DEFAULT_HOT_TAB_CATEGORY_ID = "1"

    companion object {
        fun newInstance(categoryId: String): HomeTabFragment {
            val args = Bundle()
            args.putString("categoryId", categoryId)
            val fragment = HomeTabFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        // 在super之前，保证createLayoutManager()被调用时，categoryId 已经取到了
        categoryId = arguments?.getString("categoryId", DEFAULT_HOT_TAB_CATEGORY_ID)
        super.onViewCreated(view, savedInstanceState)

        viewModel = ViewModelProvider(this)[HomeViewModel::class.java]

        enableLoadMore {
            queryTabCategoryList(CacheStrategy.NET_ONLY)
        }

        queryTabCategoryList(CacheStrategy.CACHE_FIRST)
    }

    override fun onRefresh() {
        super.onRefresh()
        queryTabCategoryList(CacheStrategy.NET_CACHE)
    }

    override fun createLayoutManager(): LayoutManager {
        val isHotTab = TextUtils.equals(categoryId, DEFAULT_HOT_TAB_CATEGORY_ID)
        return if (isHotTab) super.createLayoutManager() else GridLayoutManager(context, 2)
    }

    private fun queryTabCategoryList(cacheStrategy: Int) {
        viewModel.queryTabCategoryList(cacheStrategy, categoryId!!, pageIndex)
            .observe(viewLifecycleOwner) {
                if (it != null) {
                    updateUI(it)
                } else {
                    finishRefresh(null)
                }
            }
    }


    private fun updateUI(data: HomeModel) {
        val dataItems = mutableListOf<HiDataItem<*, *>>()
        data.bannerList?.let {
            dataItems.add(BannerItem(it))
        }

        data.subcategoryList?.let {
            dataItems.add(GridItem(it))
        }

        data.goodsList?.forEachIndexed { index, goodsModel ->
            dataItems.add(GoodsItem(goodsModel, TextUtils.equals(categoryId, DEFAULT_HOT_TAB_CATEGORY_ID)))
        }

        finishRefresh(dataItems)
    }
}